/**
 * 
 */
package com.asset.salesforce.controller.pages;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.asset.salesforce.domain.Appointment;
import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.service.AppointmentService;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.LeadService;

// TODO: Auto-generated Javadoc
/**
 * The Class AppointmentController.
 *
 * @author Hisham
 */
@Controller
public class AppointmentController {

	/** The employee service. */
	@Autowired
	private EmployeeService employeeService;
	
	/** The contact service. */
	@Autowired
	private ContactService contactService;
	
	/** The lead service. */
	@Autowired
	private LeadService leadService;
	
	/** The appointment service. */
	@Autowired
	private AppointmentService appointmentService;
	
	/** The calendar service. */
	@Autowired
	private CalendarService calendarService;
	
	/**
	 * Gets the new appointment page.
	 *
	 * @param session the session
	 * @param model the model
	 * @param response the response
	 * @param request the request
	 * @param id the id
	 * @return the new appointment page
	 */
	@RequestMapping(value = "/newAppointment", method = RequestMethod.GET)
	public String getNewAppointmentPage(HttpSession session, Model model,HttpServletResponse response,HttpServletRequest request,@RequestParam Integer id) {
		if (SecurityUtils.getSubject().hasRole("appointmentAdd")){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if(null ==session.getAttribute("userDetails")){
				return "redirect:login";
			}
			Employee employee = (Employee)session.getAttribute("userDetails");
			List<Employee>employees = employeeService.getAllCompanyEmployess(employee.getCompany().getCompanyName());
			model.addAttribute("employees",employees);
			model.addAttribute("parentId", id);
			List<Contact>contacts = contactService.getContactsByParentType(id, "lead");
			model.addAttribute("contacts",contacts);
			model.addAttribute("appointmentDTO",new Appointment());
			return "createAppointmentPage";
			}
			else{
				return "accessDenied";
			}
	}
	
	/**
	 * Gets the edits the appointment page.
	 *
	 * @param session the session
	 * @param model the model
	 * @param response the response
	 * @param request the request
	 * @param id the id
	 * @param parentId the parent id
	 * @return the edits the appointment page
	 */
	@RequestMapping(value = "/editAppointment", method = RequestMethod.GET)
	public String getEditAppointmentPage(HttpSession session, Model model,HttpServletResponse response,HttpServletRequest request,@RequestParam Integer id
			,@RequestParam Integer parentId) {
		if (SecurityUtils.getSubject().hasRole("appointmentEdit")){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if(null ==session.getAttribute("userDetails")){
				return "redirect:login";
			}
			Employee employee = (Employee)session.getAttribute("userDetails");
			List<Employee>employees = employeeService.getAllCompanyEmployess(employee.getCompany().getCompanyName());
			model.addAttribute("employees",employees);
			model.addAttribute("parentId", parentId);
			List<Contact>contacts = contactService.getContactsByParentType(id, "lead");
			model.addAttribute("contacts",contacts);
			Appointment appointment = appointmentService.getById(id);
			model.addAttribute("appointmentDTO",appointment);
			return "editAppointmentPage";
			}
			else{
				return "accessDenied";
			}
	}
	
	/**
	 * Post new appointment.
	 *
	 * @param model the model
	 * @param session the session
	 * @param request the request
	 * @param appointmentForm the appointment form
	 * @param result the result
	 * @return the string
	 */
	@RequestMapping(value="/newAppointment",method=RequestMethod.POST)
	public String postNewAppointment(Model model,HttpSession session,HttpServletRequest request,@Valid @ModelAttribute("appointmentDTO") Appointment appointmentForm,
			BindingResult result) {
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:login";
		}

		Appointment appointment = new Appointment();
		if(appointmentForm.getSalesMan() != null){
			appointment.setSalesMan(employeeService.getById(appointmentForm.getSalesMan().getId()));
		}
		if(appointmentForm.getContactedPerson() != null){
			appointment.setContactedPerson(contactService.getById(appointmentForm.getContactedPerson().getId()));
		}
		if(appointmentForm.getDay() != null){
			appointment.setDay(appointmentForm.getDay());
		}
		if(appointmentForm.getDate() != null){
			appointment.setDate(appointmentForm.getDate());
		}
		if(appointmentForm.getStartTime() != null){
			appointment.setStartTime(appointmentForm.getStartTime());
		}
		if(appointmentForm.getComment() != null){
			appointment.setComment(appointmentForm.getComment());
		}
		if(appointmentForm.getNextFollowUp() != null){
			appointment.setNextFollowUp(Boolean.valueOf(appointmentForm.getNextFollowUp()));
		}
		if(appointmentForm.getFollowUpType() != null){
			appointment.setFollowUpType(appointmentForm.getFollowUpType());
		}
		if(appointmentForm.getFollowUpDate() != null){
			appointment.setFollowUpDate(appointmentForm.getFollowUpDate());
		}
		if(appointmentForm.getFollowUpDetails()!= null){
			appointment.setFollowUpDetails(appointmentForm.getFollowUpDetails());
		}
		if(appointmentForm.getDiscountDone() != null){
			appointment.setDiscountDone(appointmentForm.getDiscountDone());
		}
		if(appointmentForm.getCompatitorOffer()!= null){
			appointment.setCompatitorOffer(appointmentForm.getCompatitorOffer());
		}
		if(appointmentForm.getDealClosingDone() != null){
			appointment.setDealClosingDone(appointmentForm.getDealClosingDone());
		}
		if(appointmentForm.getReplyPeriod() != null){
			appointment.setReplyPeriod(appointmentForm.getReplyPeriod());
		}
		if(appointmentForm.getDealClosingReason() != null){
			appointment.setDealClosingReason(appointmentForm.getDealClosingReason());
		}
		if(appointmentForm.getMeetingDone() != null){
			appointment.setMeetingDone(appointmentForm.getMeetingDone());
		}
		if(appointmentForm.getEndTime() != null){
			appointment.setEndTime(appointmentForm.getEndTime());
		}
		if(appointmentForm.getCustomerNeed() != null){
			appointment.setCustomerNeed(appointmentForm.getCustomerNeed());
		}
		if(appointmentForm.getDemoDone() != null){
			appointment.setDemoDone(appointmentForm.getDemoDone());
		}
		if(appointmentForm.getOfferSubmitted() != null){
			appointment.setOfferSubmitted(appointmentForm.getOfferSubmitted());
		}
		if(appointmentForm.getConfirmationDateExpected() != null){
			appointment.setConfirmationDateExpected(appointmentForm.getConfirmationDateExpected());
		}
		if(appointmentForm.getDiscountDone() != null){
			appointment.setDiscountDone(appointmentForm.getDiscountDone());
		}
		if(appointmentForm.getDealClosingReason() != null){
			appointment.setDealClosingReason(appointmentForm.getDealClosingReason());
		}
		appointment.setParentId(appointmentForm.getParentId());
		appointment.setParentType("lead");
		appointment.setDateCreated(new Date());
		try {
			appointmentService.add(appointment);
		} catch (Exception ex) {
			ex.printStackTrace();
			List<Employee>employees = employeeService.getAllCompanyEmployess(userDetails.getCompany().getCompanyName());
			model.addAttribute("employees",employees);
			model.addAttribute("parentId", appointmentForm.getParentId());
			List<Contact>contacts = contactService.getContactsByParentType(appointmentForm.getParentId(), "lead");
			model.addAttribute("contacts",contacts);
			model.addAttribute("timeError",ex.getMessage());
			model.addAttribute("appointmentDTO", appointmentForm);
			return "newAppointment";
		}
		calendarService.appointmentEvent(appointment);
		return "redirect:leads";
	}
	
	/**
	 * Post edit appointment.
	 *
	 * @param model the model
	 * @param session the session
	 * @param request the request
	 * @param appointmentForm the appointment form
	 * @param result the result
	 * @return the string
	 */
	@RequestMapping(value="/editAppointment",method=RequestMethod.POST)
	public String postEditAppointment(Model model,HttpSession session,HttpServletRequest request,@Valid @ModelAttribute("appointmentDTO") Appointment appointmentForm,
			BindingResult result) {
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:login";
		}

		Appointment appointment = new Appointment();
		if(appointmentForm.getSalesMan() != null){
			appointment.setSalesMan(employeeService.getById(appointmentForm.getSalesMan().getId()));
		}
		if(appointmentForm.getContactedPerson() != null){
			appointment.setContactedPerson(contactService.getById(appointmentForm.getContactedPerson().getId()));
		}
		if(appointmentForm.getDay() != null){
			appointment.setDay(appointmentForm.getDay());
		}
		if(appointmentForm.getDate() != null){
			appointment.setDate(appointmentForm.getDate());
		}
		if(appointmentForm.getStartTime() != null){
			appointment.setStartTime(appointmentForm.getStartTime());
		}
		if(appointmentForm.getComment() != null){
			appointment.setComment(appointmentForm.getComment());
		}
		if(appointmentForm.getNextFollowUp() != null){
			appointment.setNextFollowUp(Boolean.valueOf(appointmentForm.getNextFollowUp()));
		}
		if(appointmentForm.getFollowUpType() != null){
			appointment.setFollowUpType(appointmentForm.getFollowUpType());
		}
		if(appointmentForm.getFollowUpDate() != null){
			appointment.setFollowUpDate(appointmentForm.getFollowUpDate());
		}
		if(appointmentForm.getFollowUpDetails()!= null){
			appointment.setFollowUpDetails(appointmentForm.getFollowUpDetails());
		}
		if(appointmentForm.getDiscountDone() != null){
			appointment.setDiscountDone(appointmentForm.getDiscountDone());
		}
		if(appointmentForm.getCompatitorOffer()!= null){
			appointment.setCompatitorOffer(appointmentForm.getCompatitorOffer());
		}
		if(appointmentForm.getDealClosingDone() != null){
			appointment.setDealClosingDone(appointmentForm.getDealClosingDone());
		}
		if(appointmentForm.getReplyPeriod() != null){
			appointment.setReplyPeriod(appointmentForm.getReplyPeriod());
		}
		if(appointmentForm.getDealClosingReason() != null){
			appointment.setDealClosingReason(appointmentForm.getDealClosingReason());
		}
		if(appointmentForm.getMeetingDone() != null){
			appointment.setMeetingDone(appointmentForm.getMeetingDone());
		}
		if(appointmentForm.getEndTime() != null){
			appointment.setEndTime(appointmentForm.getEndTime());
		}
		if(appointmentForm.getCustomerNeed() != null){
			appointment.setCustomerNeed(appointmentForm.getCustomerNeed());
		}
		if(appointmentForm.getDemoDone() != null){
			appointment.setDemoDone(appointmentForm.getDemoDone());
		}
		if(appointmentForm.getOfferSubmitted() != null){
			appointment.setOfferSubmitted(appointmentForm.getOfferSubmitted());
		}
		if(appointmentForm.getConfirmationDateExpected() != null){
			appointment.setConfirmationDateExpected(appointmentForm.getConfirmationDateExpected());
		}
		if(appointmentForm.getDiscountDone() != null){
			appointment.setDiscountDone(appointmentForm.getDiscountDone());
		}
		if(appointmentForm.getDealClosingReason() != null){
			appointment.setDealClosingReason(appointmentForm.getDealClosingReason());
		}
		appointment.setParentId(appointmentForm.getParentId());
		appointment.setParentType("lead");
		appointment.setDateModified(new Date());
		try {
			appointmentService.saveOrupdate(appointment);
		} catch (Exception ex) {			
			List<Employee>employees = employeeService.getAllCompanyEmployess(userDetails.getCompany().getCompanyName());
			model.addAttribute("employees",employees);
			model.addAttribute("parentId", appointmentForm.getParentId());
			List<Contact>contacts = contactService.getContactsByParentType(appointmentForm.getParentId(), "lead");
			model.addAttribute("contacts",contacts);
			model.addAttribute("timeError",ex.getMessage());
			model.addAttribute("appointmentDTO", appointmentForm);
			return "newAppointment";
		}
		calendarService.appointmentEvent(appointment);
		return "redirect:leads";
	}
	
	/**
	 * Gets the view appointment page.
	 *
	 * @param session the session
	 * @param model the model
	 * @param response the response
	 * @param request the request
	 * @param id the id
	 * @return the view appointment page
	 */
	@RequestMapping(value = "/viewAppointment", method = RequestMethod.GET)
	public String getViewAppointmentPage(HttpSession session, Model model,HttpServletResponse response,HttpServletRequest request,@RequestParam Integer id) {
		if (SecurityUtils.getSubject().hasRole("appointmentView")){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if(null ==session.getAttribute("userDetails")){
				return "redirect:login";
			}
			Appointment appointment = appointmentService.getById(id);
			model.addAttribute("appointmentDTO",appointment);
			return "viewAppointmentPage";
			}
			else{
				return "accessDenied";
			}
	}
}
